package com.yisu.expressway.manager.website.controller.dataAnalysis;

import com.yisu.expressway.manager.domain.request.UploadImageRequest;
import com.yisu.expressway.manager.domain.response.UploadImageResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by xlt on 2017/5/3.
 */
@Controller
@RequestMapping(value = "/fileAction")
public class FileActionController extends HttpServlet {
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @RequestMapping(value = "/zipFileUploadAction.json")
    @ResponseBody
    protected UploadImageResult doGet(HttpServletRequest request, HttpServletResponse response, UploadImageRequest uploadImageRequest) throws ServletException, IOException {
        // TODO Auto-generated method stub
       return doUploadFilePost(request, response);
    }

    /**
     * 此方法用于数据解析压缩包上传，用于上抛压缩文件
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected UploadImageResult doUploadFilePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UploadImageResult uploadImageResult=new UploadImageResult();
        try {
            // TODO Auto-generated method stub
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");
            //上传保存路径
            String savePath=request.getSession().getServletContext().getRealPath("")+ File.separator+"fileUpload";
            File saveFileDir = new File(savePath);
            if (!saveFileDir.exists()) {
                // 创建临时目录
                saveFileDir.mkdirs();
            }
            InputStream is = file.getInputStream();
            String originalFileName = file.getOriginalFilename();
            FileOutputStream out = new FileOutputStream(savePath + File.separator + originalFileName);
            //创建一个缓冲区
            byte buffer[] = new byte[1024];
            //判断输入流中的数据是否已经读完的标致
            int len = 0;
            while ((len = is.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            //关闭输出流
            out.close();
            //关闭输入流
            is.close();
            uploadImageResult.setState("SUCCESS ");
        }
        catch (Exception ex)
        {
            String i="0";
        }
        return uploadImageResult;
    }
}
